package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 用户Token校验器
 *
 * @Author mr.lcc
 * @Data 2025/6/20 12:14
 */
@Component
@RequiredArgsConstructor // 构造器注入
@EnableConfigurationProperties(AuthProperties.class) // 注入IOC
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final JwtTool jwtTool;

    /**
     * 拦截处理
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Http请求实例和响应实例
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 2.获取请求路径 获取相对路径
        String path = request.getURI().getPath();

        // 3.判断是否可放行(判断当前请求路径是否是白名单,使用antPathMatcher进行匹配)
        long excludeCount = authProperties.getExcludePaths()
                .stream()
                .filter(excludePath -> antPathMatcher.match(excludePath, path))
                .count();
        if (excludeCount > 0) {
            log.info("放行");
            return chain.filter(exchange);
        }

        // 4.获取请求头重的token
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        // 5.校验token信息为空返回401
        if (StrUtil.isBlank(token)) {
            log.error("拦截token为空！");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            // 6.解析Token
            Long userId = jwtTool.parseToken(token);
            if (userId == null) {
                log.error("Jwt参数解析为空！");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //7.解析令牌成功，设置用户信息到请求头
            // 请求头中设置用户Id
            request.mutate().header("user-info", userId.toString());

            // 8.解析成功放行
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            // 9.解析失败响应401
            log.error("Jwt参数解析失败！");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    /**
     * 处理等级
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
